package com.gxy.learn.office.web;

import com.gxy.learn.cu.utils.io.FileUtils;
import com.gxy.learn.office.excel.ExcelUtils;
import com.gxy.learn.office.excel.ExcelVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.poi.util.IOUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * Description(文件测试)
 * author: Gao xueyong
 * Create at: 2020/3/22 8:09 下午
 */
@Slf4j
@RestController
@RequestMapping("/gxy/file")
public class FileController {

    //http://localhost:7001/javaUtilsProject/gxy/file/downloadExcel
    @RequestMapping(value = "/downloadExcel", method = RequestMethod.GET)
    public void downLoadExcel(HttpServletResponse response) throws Exception {
        String rootPath = this.getClass().getClassLoader().getResource("").getPath();
        String fileName = "exportXlsx.xlsx";
        String filePath = "excelModel" + File.separator + fileName;
//        File file = new File(rootPath + filePath);
//        if (!file.exists()) {
//            throw new Exception("文件不存在！下载失败");
//        }
//        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//        response.setContentType("application/x-excel");
//        response.setCharacterEncoding("UTF-8");
//        IOUtils.copy(new FileInputStream(file), response.getOutputStream());

        filePath = "/Users/gaoxueyong/Documents/export/文档3.xlsx";
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("application/msexcel");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(FileUtils.readFilePathToByteNIO(filePath));
        IOUtils.closeQuietly(outputStream);
    }

    @RequestMapping(value = "/uploadExcel", method = RequestMethod.POST)
    public void uploadExcel(MultipartHttpServletRequest request) throws Exception {
        MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
        MultipartFile muFile = multiFileMap.getFirst("muFile");
        String fileName = muFile.getOriginalFilename();
        List<ExcelVo> result = new ArrayList<>();
        if (fileName.endsWith(".xlsx")) {
            result = ExcelUtils.readExcelXlsx(muFile.getInputStream(), 1);
        } else if (fileName.endsWith(".xls")) {
            result = ExcelUtils.readExcelXls(muFile.getInputStream(), 1);
        } else {
            throw new RuntimeException("文件格式不正确！目前仅支持xlsx、xls格式大问题上传");
        }
        for (ExcelVo vo : result) {
            log.info("=======================读取表格{}数据开始=======================", vo.getSheetName());
            for (List<String> rowInfo : vo.getSheetData()) {
                log.info(rowInfo.toString());
            }
            log.info("=======================读取表格{}数据结束=======================", vo.getSheetName());
        }

    }


    /**
     * 下载文件并打包zip
     * http://commons.apache.org/proper/commons-compress/download_compress.cgi
     *
     * 生成zip文件dmo
     *  文档
     *      文档1.txt
     *      文档2.txt
     *      文档3.xlsx
     *  头像
     *      head1.jpg
     *      head2.jpg
     *      head3.jpg
     * @param response
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void exportDate(HttpServletResponse response) {
        OutputStream outputStream = null;
        try {
            Map<String, List<String>> fileMap = new HashMap<>();
            fileMap.put("头像", Arrays.asList("/Users/gaoxueyong/Documents/export/head1.jpg",
                    "/Users/gaoxueyong/Documents/export/head2.jpg", "/Users/gaoxueyong/Documents/export/head3.jpg"));
            fileMap.put("文档", Arrays.asList("/Users/gaoxueyong/Documents/export/文档1.txt",
                    "/Users/gaoxueyong/Documents/export/文档2.txt", "/Users/gaoxueyong/Documents/export/文档3.xlsx"));
//            response.setContentType("application/msexcel");
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("UTF-8");
            String fileName = "zip文件";
            String downloadFileName = URLEncoder.encode(fileName + System.currentTimeMillis() + "." + ArchiveStreamFactory.ZIP, "UTF-8");
            response.addHeader("Content-Disposition", String.format("attachment;filename=%s", downloadFileName));
            response.flushBuffer();
            outputStream = response.getOutputStream();
            outputStream.write(FileUtils.toZip(fileMap));
        } catch (IOException e) {
            log.error("批量下载文件失败！", e);
        } finally {
            IOUtils.closeQuietly(outputStream);
        }
    }

}

